package com.s7.widget.admix;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.s7.widget.R;
import com.s7.widget.admix.holder.EditHolder;
import com.s7.widget.admix.holder.ImageHolder;
import com.s7.widget.utils.ImageUtils;

import java.util.ArrayList;
import java.util.List;

public class AdmixAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnTouchListener, View.OnFocusChangeListener {

    protected Context context;
    List<AdmixData> datas;

    public AdmixAdapter(Context context) {
        this.context = context;
        if (datas == null) {
            datas = new ArrayList<>();
            datas.add(new AdmixData());
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if (viewType == 1) {
            view = this.getView(parent, getImageId());
            return new ImageHolder(view);
        } else {
            view = this.getView(parent, getEditId());
            return new EditHolder(view);
        }
    }

    private View getView(ViewGroup parent, int id) {
        return LayoutInflater.from(parent.getContext()).inflate(id, parent, false);
    }

    protected int getImageId() {
        return R.layout.admix_image;
    }

    protected int getEditId() {
        return R.layout.admix_edit;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ImageHolder) {
            bindImage((ImageHolder) holder, position, datas.get(position));
        }

        if (holder instanceof EditHolder) {
            bindEdit((EditHolder) holder, position, datas.get(position));
        }
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    @Override
    public int getItemViewType(int position) {
        AdmixData data = datas.get(position);
        if (TextUtils.isEmpty(data.getUrl())) {
            return 0;
        } else {
            return 1;
        }
    }

    protected void bindImage(ImageHolder holder, final int position, AdmixData admixData) {
        setImageUrl(admixData.getUrl(), (ImageView) holder.getView(R.id.image_ico));
        holder.getView(R.id.image_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 删除图片
                delImage(position);
            }
        });
    }

    /**
     * 焦点所在位置
     */
    private int selectedEditPosition = -1;
    private int selection = -1;

    protected void bindEdit(EditHolder holder, final int position, final AdmixData admixData) {
        final EditText editText = holder.getItemView();
        editText.setOnTouchListener(this);
        editText.setOnFocusChangeListener(this);
        editText.setTag(position);
        if (TextUtils.isEmpty(admixData.getInput())) {
            admixData.setInput("");
            editText.setText("");
        } else {
            editText.setText(admixData.getInput());
        }

        if (selectedEditPosition != -1 && position == selectedEditPosition) {
            // 保证每个时刻只有一个EditText能获取到焦点
            editText.requestFocus();
            if (selection == -1) {
                selection = editText.getText().length();
            }
            if (selection > editText.getText().length()) {
                selection = editText.getText().length();
            }
            editText.setSelection(selection);
        } else {
            editText.clearFocus();
        }
        editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                    EditText edit = (EditText) v;
                    admixData.setInput(edit.getText().toString());
                    onBackspacePress(edit, position);
                }
                return false;
            }
        });
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            EditText editText = (EditText) v;
            selectedEditPosition = (int) editText.getTag();
        }
        return false;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            ((EditText) v).addTextChangedListener(watcher);
        } else {
            ((EditText) v).removeTextChangedListener(watcher);
        }
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!TextUtils.isEmpty(editable) && selectedEditPosition != -1) {
                datas.get(selectedEditPosition).setInput(editable.toString());
            }
        }
    };

    /**
     * 加载图片
     * @param url
     * @param iv
     */
    private void setImageUrl(String url, ImageView iv) {
        ImageUtils.setImageUrl(context, url, iv);
    }

    /**
     * 添加网络图片
     *
     * @param url
     */
    public void addImage(String url) {
        AdmixData data = new AdmixData();
        data.setUrl(url);
        if (TextUtils.isEmpty(datas.get(datas.size() - 1).getUrl())
                && TextUtils.isEmpty(datas.get(datas.size() - 1).getInput())) {
            if (selectedEditPosition < 0) {
                selectedEditPosition = 0;
            }
            datas.add(selectedEditPosition, data);
        } else {
            datas.add(selectedEditPosition + 1, data);
        }
        if (selectedEditPosition + 1 == datas.size() - 1) {
            datas.add(new AdmixData());
        }
        notifyDataSetChanged();
    }

    /**
     * 添加文字
     * @param end
     */
    public void append(String end) {
        AdmixData data;
        if (selectedEditPosition == -1) {
            data = datas.get(0);
        } else {
            data = datas.get(selectedEditPosition);
        }
        if (TextUtils.isEmpty(data.getUrl())) {
            if (!TextUtils.isEmpty(data.getInput())) {
                data.setInput(data.getInput() + end);
            } else {
                data.setInput(end);
            }
        } else {
            AdmixData data1 = new AdmixData();
            data1.setInput(end);
            datas.add(selectedEditPosition + 1, data1);
        }
        notifyDataSetChanged();
    }

    /**
     * 删除图片
     *
     * @param position
     */
    public void delImage(int position) {
        if (position < selectedEditPosition) {
            selectedEditPosition = selectedEditPosition - 1;
        }
        if (datas.size() > position) {
            datas.remove(position);
            notifyDataSetChanged();
        }
    }

    /**
     * 文字回删
     *
     * @param edit
     * @param position
     */
    public void onBackspacePress(EditText edit, int position) {
        int startSelection = edit.getSelectionStart();
        /**
         * 判断光标是否在文本最前方
         */
        if (startSelection == 0) {
            /**
             * 当前文本不是第一个文本
             */
            if (position > 0) {
                AdmixData data = datas.get(position - 1);
                selection = 0;
                /**
                 * 判断上一个是否是图片
                 */
                if (!TextUtils.isEmpty(data.getUrl())) {
                    selectedEditPosition = selectedEditPosition - 1;
                    delImage(position - 1);
                } else {
                    if (TextUtils.isEmpty(data.getInput())) {
                        selection = 0;
                    } else {
                        selection = data.getInput().length();
                    }

                    /**
                     * 不是图片合并文本框
                     */
                    data.setInput(data.getInput() + edit.getText().toString());
                    datas.remove(position);
                    onLocation();
                    notifyDataSetChanged();
                }
            }
        }
    }

    /**
     * 定位
     */
    private void onLocation() {
        if (selectedEditPosition > 0) {
            selectedEditPosition = selectedEditPosition - 1;
            if (!TextUtils.isEmpty(datas.get(selectedEditPosition).getUrl())) {
                onLocation();
            }
        }
    }

    /**
     * 插入数据
     * @param datas
     */
    public void setDatas(List<AdmixData> datas) {
        this.datas.clear();
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }

    /**
     * 获取数据
     * @return
     */
    public List<AdmixData> getDatas() {
        return datas;
    }
}
